package tbao.net.searsh.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.tbao.common.to.es.SkuEsModel;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tbao.net.searsh.config.TaoBaoElasticSearchConfig;
import tbao.net.searsh.constant.Esconstant;
import tbao.net.searsh.service.ProductSaveService;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl  implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;


    /**
     * 商品上架
     * @param skuEsModels
     */
    @SneakyThrows
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) {
        //保存到ES中
        BulkRequest bulkRequest=new BulkRequest();
       for(SkuEsModel model:skuEsModels){
           //构造保存请求
           IndexRequest indexRequest = new IndexRequest(Esconstant.PRODUCT_INDEX);
           indexRequest.id(model.getSkuId().toString());
           String s = JSON.toJSONString(model);
           indexRequest.source(s, XContentType.JSON);
           bulkRequest.add(indexRequest);
       }

            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, TaoBaoElasticSearchConfig.COMMON_OPTIONS);
             boolean b = bulk.hasFailures();
        List<Object> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();

        }).collect(Collectors.toList());
        log.info("商品上架完成,{}",collect,bulk.toString());

        return b;

    }
}
